package com.gph.saviorframework.shiro.filter;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created by savior on 2016/8/29.
 */
public class VerificationFilter extends AccessControlFilter {

    private boolean verificationEnabled = true;

    private String verificationParam = "verificationCode";

    private String failureKeyAttr = "shiroLoginFailure";

    public boolean isVerificationEnabled() {
        return verificationEnabled;
    }

    public void setVerificationEnabled(boolean verificationEnabled) {
        this.verificationEnabled = verificationEnabled;
    }

    public String getVerificationParam() {
        return verificationParam;
    }

    public void setVerificationParam(String verificationParam) {
        this.verificationParam = verificationParam;
    }

    public String getFailureKeyAttr() {
        return failureKeyAttr;
    }

    public void setFailureKeyAttr(String failureKeyAttr) {
        this.failureKeyAttr = failureKeyAttr;
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {

        request.setAttribute("verificationEnabled",verificationEnabled);

        HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
        if(verificationEnabled == false || !httpServletRequest.getMethod().equalsIgnoreCase("post")){
            return true;
        }

        //验证填写的验证码是否正确
        String code = httpServletRequest.getParameter(verificationParam);
        if(StringUtils.isEmpty(code)){
            return false;
        }

        HttpSession session = httpServletRequest.getSession(false);
        if(session == null){
            return false;
        }

        if(httpServletRequest.getParameter(verificationParam).equals(session.getAttribute(verificationParam))){
            return true;
        }
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        request.setAttribute(failureKeyAttr,"Verification Error");
        return true;
    }
}
